import { useStore } from "vuex";
import { computed } from "vue";

const useCommonCartEffect = (shopId = null) => {
  const store = useStore();
  const addToCart = (shopId, productId, info, shopName) => {
    store.commit("addToCartStore", { shopId, productId, info, shopName });
  };
  const minusToCart = (shopId, productId, info, shopName) => {
    store.commit("minusToCartStore", { shopId, productId, info, shopName });
  };

  const cartList = store.state.cartList;
  const shopName = computed(() => {
    return cartList[shopId]?.shopName || "";
  });

  const dataList = computed(() => {
    return cartList[shopId]?.productList || {};
  });

  // 计算属性相关
  let result = computed(() => {
    let res = { totalCount: 0, totalPrice: 0, allCheck: true };
    const shopInfo = cartList[shopId]?.productList;
    for (let k in shopInfo) {
      if (shopInfo[k].count) {
        res.totalCount += parseInt(shopInfo[k].count);
      }
      if (shopInfo[k].count && shopInfo[k].check) {
        res.totalPrice += shopInfo[k].count * shopInfo[k].price;
      }
      if (!shopInfo[k].check && shopInfo[k].count > 0) {
        res.allCheck = false;
      }
    }
    res.totalPrice = res.totalPrice.toFixed(2);
    return res;
  });

  return {
    addToCart,
    minusToCart,
    shopName,
    cartList,
    dataList,
    result,
  };
};

export { useCommonCartEffect };
